package logic

import (
	"context"
	"errors"
	"hzjt-oam/rpc/sys/internal/config"
	"hzjt-oam/rpc/sys/internal/svc"
	"hzjt-oam/rpc/sys/model"
	"hzjt-oam/rpc/sys/pb"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *pb.UserRegisterReq) (*pb.UserRegisterResp, error) {
	// 判断code是否一致
	code, err := l.svcCtx.RDB.Get(l.ctx, in.SysUser.Email).Result()
	if err != nil {
		return nil, errors.New("该邮箱的验证码为空")
	}
	if code != in.VerificationCode {
		err = errors.New("验证码错误")
	}
	// 判断用户名是否已存在
	cnt, err := l.svcCtx.UserModel.FindOneByEmail(l.ctx, in.SysUser.Email)
	if err != nil || len(cnt.Email) > 0 {
		err = errors.New("用户名已存在")
		return nil, err
	}

	dept_model, err := l.svcCtx.DeptModel.FindByName(l.ctx, in.SysUser.DeptName)
	if err != nil {
		err = errors.New("部门不存在")
		return nil, err
	}

	role_model, err := l.svcCtx.RoleModel.FindByName(l.ctx, in.SysUser.RoleName)
	if err != nil {
		err = errors.New("角色不存在")
		return nil, err
	}

	user := &model.SysUser{
		Id:             0,
		Name:           in.SysUser.Name,
		NickName:       in.SysUser.NickName,
		Avatar:         in.SysUser.Avatar,
		Password:       config.Md5(config.Md5(in.SysUser.Password)),
		Salt:           in.SysUser.Salt,
		Email:          in.SysUser.Email,
		Mobile:         in.SysUser.Mobile,
		Status:         in.SysUser.Status,
		DeptId:         dept_model.Id,
		CreateBy:       in.SysUser.Name,
		CreateTime:     time.Now().Unix(),
		LastUpdateBy:   in.SysUser.Name,
		LastUpdateTime: time.Now().Unix(),
		DelFlag:        0,
		RoleId:         role_model.Id,
	}

	_, err = l.svcCtx.UserModel.Insert(l.ctx, user)
	if err != nil {
		err = errors.New("用户创建失败")
		return nil, err
	}

	return &pb.UserRegisterResp{}, nil
}
